import re

from py_ini_config_modules.system_functions import eprint, read_ini_file


def ini_config_set(file, section, var, value, noindent, com_symbol, view_comments, separator=None):
    separator_set = False
    if separator is None:
        separator = '='
    else:
        separator_set = True
    config = read_ini_file(file)
    written = False
    current_section = False
    section_start_index = -1
    commented_index = -1
    uncommented_index = -1

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_start_index = i
            else:
                current_section = False
        if re.fullmatch(f'\s*{com_symbol}*\s*{var}\s*', line[0]) and current_section:
            if com_symbol not in config[i]:
                uncommented_index = i
            elif len(line) > 1 and line[1] == value:
                commented_index = i

    if commented_index != -1 and view_comments: # 1, 3
        config[commented_index] = config[commented_index].lstrip().lstrip(com_symbol)
        written = True
        if uncommented_index != -1:
            config[uncommented_index] = com_symbol + config[uncommented_index]
        if noindent:
            config[commented_index] = config[commented_index].lstrip()
    elif uncommented_index != -1: # 2
        if separator.strip() not in config[uncommented_index]:
            # config[i] = var + separator + value
            config[uncommented_index] = config[uncommented_index].rstrip() + separator + value
        elif separator_set:
            indx = config[uncommented_index].index(separator.strip()) - 1
            while config[uncommented_index][indx] == ' ':
                indx -= 1
            config[uncommented_index] = config[uncommented_index][:indx + 1] + separator + value
        else:
            indx = config[uncommented_index].index(separator.strip()) + 1
            while config[uncommented_index][indx] == ' ':
                indx += 1
            config[uncommented_index] = config[uncommented_index][:indx] + value
        written = True
    # if config[i].lstrip().startswith(com_symbol):
    #     config[i] = config[i].lstrip().lstrip(com_symbol).lstrip()
    # written = True
        if noindent:
            config[uncommented_index] = config[uncommented_index].lstrip()
    if not written:
        if section_start_index != -1:
            config.insert(section_start_index + 1, var + separator + value)
        else:
            if len(config) > 0 and config[-1].strip() != '':
                config.append('')
            elif len(config) == 0 or (len(config) == 1 and config[0].strip() == ''):
                config = []
            config.append('[' + section + ']')
            config.append(var + separator + value)
    return config


def ini_config_comment(file, section, com_symbol, var=None, separator='='):
    config = read_ini_file(file)
    current_section = False
    section_found = False
    var_commented = False

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_found = True
            else:
                current_section = False
        elif current_section:
            if var is None:
                if not line[0].startswith(com_symbol):
                    config[i] = com_symbol + config[i]
            else:
                if line[0] == var:
                    config[i] = com_symbol + config[i]
                    var_commented = True
                # Переменные могут встречаться несколько раз!
                # elif line[0] == '#' + var:
                #     eprint('Переменная уже была закомментирована')
                #     return False
    if not section_found:
        eprint('Указанная секция не существует')
        return False
    if section_found and var is not None and not var_commented:
        eprint('Переменная не найдена')
        return False

    return config


def ini_config_del(file, section, var, flush, com_symbol, separator='='):
    config = read_ini_file(file)
    new_config = []
    current_section = False
    section_found = False
    var_deleted = False
    vars_left_in_section = False
    section_index = -1
    last_commented_index = -1
    commented_vars_cnt = 0

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            new_config.append(config[i])
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_found = True
                section_index = i
            else:
                current_section = False
        elif current_section:
            if re.fullmatch(f'\s*{com_symbol}*\s*{var}\s*', line[0]):
                if not line[0].lstrip().startswith(com_symbol):
                    var_deleted = True
                    continue
                else:
                    last_commented_index = i
                    commented_vars_cnt += 1
            else:
                vars_left_in_section = True
        new_config.append(config[i])

    if commented_vars_cnt > 1:
        vars_left_in_section = True
    if not section_found:
        eprint('Указанная секция не существует')
        return False
    elif not var_deleted:
        if last_commented_index != -1:
            new_config = new_config[:last_commented_index] + new_config[last_commented_index + 1:]
        elif section_index != -1 and flush:
            new_config = new_config[:section_index] + new_config[section_index + 1:]
        else:
            eprint('Переменная не найдена')
            return False
    if not vars_left_in_section and section_index != -1 and flush:
        new_config = new_config[:section_index] + new_config[section_index + 1:]

    while len(new_config) > 0 and new_config[0].strip() == '':
        new_config = new_config[1:]
    while len(new_config) > 0 and new_config[-1].strip() == '':
        new_config = new_config[:-1]
    return new_config


def ini_config_get(file, section, var, separator='='):
    config = read_ini_file(file)

    current_section = False

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
            else:
                current_section = False
        elif current_section:
            if line[0] == var:
                return line[1] if len(line) > 1 else var
    return False


def ini_config_get_commented(file, section, var, com_symbol, separator='='):
    config = read_ini_file(file)

    current_section = False
    res = []
    var_without_value_found = False

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
            else:
                current_section = False
        elif current_section:
            if re.fullmatch(f'\s*{com_symbol}\s*{var}\s*', line[0]):
                # return line[1] if len(line) > 1 else var
                if len(line) > 1:
                    res.append(line[1])
                else:
                    var_without_value_found = True
    if len(res) > 0:
        return res
    elif var_without_value_found:
        return [var]
    return False


def ini_config_is_set(file, section, var=None, separator='='):
    config = read_ini_file(file)

    current_section = False

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                if var is None:
                    return 0
            else:
                current_section = False
        elif current_section:
            if line[0] == var and len(line) > 1:
                return 0
    return 1


def ini_config_uncomment(file, section, com_symbol, var=None, separator='='):

    config = read_ini_file(file)
    current_section = False
    section_found = False
    var_uncommented = False
    last_commented_index = -1

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_found = True
            else:
                current_section = False
        elif current_section:
            if var is None:
                config[i] = config[i].lstrip().lstrip(com_symbol).lstrip()
            else:
                if line[0].startswith(com_symbol) and line[0].lstrip(com_symbol).lstrip() == var:
                    last_commented_index = i
                elif line[0] == var:
                    eprint('Переменная уже была раскомментирована')
                    return False

    if last_commented_index != -1:
        config[last_commented_index] = config[last_commented_index].lstrip().lstrip(com_symbol)
        var_uncommented = True
    if not section_found:
        eprint('Указанная секция не существует')
        return False
    elif var is not None and not var_uncommented:
        eprint('Переменная не найдена')
        return False
    return config


def ini_config_del_section(file, section, separator='='):
    config = read_ini_file(file)
    current_section = False
    section_found = False
    new_config = []

    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            if not current_section:
                new_config.append(line)
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_found = True
            else:
                current_section = False
        if current_section:
            continue
        new_config.append(config[i])

    if not section_found:
        eprint('Указанная секция не существует')
        return False

    while len(new_config) > 0 and new_config[0].strip() == '':
        new_config = new_config[1:]
    while len(new_config) > 0 and new_config[-1].strip() == '':
        new_config = new_config[:-1]
    return new_config


def ini_config_is_empty(file, section, separator='='):
    config = read_ini_file(file)
    current_section = False
    section_is_empty = True
    section_found = False
    for i in range(len(config)):
        raw_line = config[i]
        line = raw_line.strip()
        if line == '':
            continue
        line = line.split(separator.strip())
        for j in range(len(line)):
            line[j] = line[j].strip()
        if len(line) == 1 and line[0].startswith('['):
            line[0] = line[0][1:-1]
            if line[0] == section:
                current_section = True
                section_found = True
            else:
                current_section = False
        elif current_section:
            section_is_empty = False
    if not section_found:
        eprint('Указанная секция не существует')
        return False

    return not section_is_empty
